package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookContrlooer {
    @Autowired
    private AddressBookService addressBookService;
    @PostMapping
    public R<String> addressBook(@RequestBody AddressBook addressBook){
        Long threadLocal = BaseContext.getThreadLocal();
        addressBook.setUserId(threadLocal);
        addressBookService.save(addressBook);
        return R.success("保存地址成功");
    }
    @PutMapping("/default")
    public  R<String> addressDefault(@RequestBody AddressBook addressBook){
        LambdaUpdateWrapper<AddressBook> updateWrapper=new LambdaUpdateWrapper();
        updateWrapper.set(AddressBook::getIsDefault,0);
        updateWrapper.eq(AddressBook::getUserId,BaseContext.getThreadLocal());
        addressBookService.update(updateWrapper);
        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);
        return R.success("设置成功");
    }
    @GetMapping("/{id}")
    public R<AddressBook> addressGet(@PathVariable Long id){
        AddressBook byId = addressBookService.getById(id);
        return R.success(byId);
    }
    @GetMapping("/default")
    public R<AddressBook> addressGetDefault(){
        LambdaQueryWrapper<AddressBook> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getIsDefault,1);
        Long threadLocal = BaseContext.getThreadLocal();
        wrapper.eq(AddressBook::getId,threadLocal);
        AddressBook one = addressBookService.getOne(wrapper);
        return R.success(one);
    }
    @GetMapping("/list")
    public R<List<AddressBook>> addressList(){
        LambdaQueryWrapper<AddressBook> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.eq(AddressBook::getUserId,BaseContext.getThreadLocal());
        List<AddressBook> list = addressBookService.list(queryWrapper);
        return R.success(list);
    }
    @DeleteMapping
    public R<String> addressDelete(@RequestParam List<Long> ids){
        addressBookService.removeByIds(ids);
        return R.success("删除成功");
    }
    @PutMapping
    public R<String> addressBookPut(@RequestBody AddressBook addressBook){
        addressBookService.updateById(addressBook);

        return R.success("修改成功");
    }
}
